<template>
  <transition name="fade">
    <div v-show="visible" class="chat-float">
      <!-- 头部 -->
      <div class="chat-header">
        <span>正在与 {{ currentChat.name }} 聊天</span>
        <i class="el-icon-close" @click="close" />
      </div>

      <!-- 主体 -->
      <div class="chat-body">
        <el-tabs v-model="activeTab">
          <!-- 对方信息 -->
          <el-tab-pane label="对方信息" name="target">
            <el-descriptions :column="1" size="mini" border>
              <el-descriptions-item
                v-for="(val, key) in target"
                :key="key"
                :label="fieldName(key)"
              >
                {{ fmtVal(val) }}
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <!-- 我的信息 -->
          <el-tab-pane label="我的信息" name="self">
            <el-descriptions :column="1" size="mini" border>
              <el-descriptions-item
                v-for="(val, key) in self"
                :key="key"
                :label="fieldName(key)"
              >
                {{ fmtVal(val) }}
              </el-descriptions-item>
            </el-descriptions>
          </el-tab-pane>

          <!-- 聊天区域 -->
          <el-tab-pane label="聊天" name="chat">
            <div class="chat-main">
              <div class="chat-main-header">
                <span>正在与 {{ currentChat.name }} 聊天</span>
              </div>
              <div class="chat-main-body">
                <div
                  v-for="message in currentChat.messages"
                  :key="message.id"
                  :class="`chat-message ${message.from === selfId ? 'self' : 'other'}`"
                >
                  <div v-if="message.from !== selfId" class="message-sender">
                    {{ message.name || '对方' }}
                  </div>
                  <div class="chat-message-content">{{ message.content }}</div>
                  <div v-if="message.from === selfId" class="message-sender self-sender">
                    {{ message.name || '我' }}
                  </div>
                </div>
              </div>
              <div class="chat-main-footer">
                <input
                  v-model="newMessage"
                  @keyup.enter="sendMessage"
                  placeholder="输入消息..."
                />
                <button @click="sendMessage">发送</button>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </div>
    </div>
  </transition>
</template>

<script>
import Stomp from 'webstomp-client';
import SockJS from 'sockjs-client';
import request from '@/utils/request';

export default {
  name: 'ChatFloat',
  data() {
    return {
      visible: false,
      activeTab: 'target',
      target: {},
      self: {},
      selfId: '',
      targetId: '',
      hrId: '', // 添加一个变量存储HR的ID
      userId: '', // 添加一个变量存储用户ID
      currentChat: {
        messages: []
      },
      newMessage: '',
      stompClient: null,
      chatId: '', // 添加 chatId 属性
    };
  },
  methods: {
    /* 外部调用入口 */
    open(row, selfType = 'HR') {
      // 直接按传入的身份取本地数据
      const selfKey = selfType === 'HR' ? 'hr_user' : 'currentUser';
      const me = JSON.parse(localStorage.getItem(selfKey) || '{}');
      console.log('原始我方信息:', me);
      console.log('原始对方信息:', row);

      const normalizedMe = this.normalize(me);
      const normalizedTarget = this.normalize(row);

      // 提取双方ID信息
      const myId = normalizedMe.id || normalizedMe.hrId || normalizedMe.userID || null;
      const targetId = normalizedTarget.id || normalizedTarget.hrId || normalizedTarget.userID || null;

      // 判断当前用户类型并正确设置双方信息
      const isHR = (myId >= 100000 && myId <= 199999);
      const isUser = (myId >= 200000 && myId <= 299999);

      // 确保hrId和userId的正确识别
      if (isHR) {
        // HR登录时
        this.self = normalizedMe;
        this.target = normalizedTarget;
        // HR端：从自身信息中获取hrId，从对方信息中获取userId
        this.hrId = myId;
        this.userId = targetId;
        this.chatId = `${this.hrId}-${this.userId}`;
        console.log('hr解析后的chatId:', this.chatId);
      } else if (isUser) {
        // 普通用户登录时
        this.self = normalizedMe;
        this.target = normalizedTarget;
        // 用户端：从对方信息中获取hrId，从自身信息中获取userId
        this.hrId = targetId;
        this.userId = myId;
        this.chatId = `${this.hrId}-${this.userId}`;
        console.log('user解析后的chatId:', this.chatId);
      } else {
        console.warn('无法识别的用户类型，ID:', myId);
      }

      console.log('解析后的HR ID:', this.hrId);
      console.log('解析后的用户 ID:', this.userId);

      this.selfId = myId;
      this.targetId = targetId;

      // 设置固定的 chatId 格式为 hrId-userId，确保两端一致
      // 无论哪一方登录，都使用 HR ID 在前，用户 ID 在后的格式
      this.chatId = `${this.hrId}-${this.userId}`;

      // 设置当前聊天对象
      this.currentChat = {
        id: this.chatId,
        name: `${this.chatId} - ${this.target.name || this.target.Name}`,
        messages: [],
      };

      this.visible = true;
      this.connect();
      this.loadChatHistory();
    },
    close() {
      this.visible = false;
      if (this.stompClient) {
        this.stompClient.disconnect();
      }
    },

    /* 统一把 row 里所有字段摊平 */
    normalize(obj) {
      const o = {};
      Object.keys(obj).forEach(k => {
        // 若后端把整条记录再包一层 data，也展开
        if (typeof obj[k] === 'object' && obj[k] !== null && !Array.isArray(obj[k])) {
          Object.assign(o, this.normalize(obj[k]));
        } else {
          o[k] = obj[k];
        }
      });
      return o;
    },

    /* 字段名转中文 */
    fieldName(str) {
      return str
        .replace(/([A-Z])/g, ' $1') // 驼峰
        .replace(/_/g, ' ') // 下划线
        .replace(/^./, m => m.toUpperCase());
    },

    /* 空值处理 */
    fmtVal(v) {
      return v === null || v === undefined || v === '' ? '-' : v;
    },

    /* WebSocket 连接 */
    connect() {
      if (this.stompClient && this.stompClient.connected) {
        this.stompClient.disconnect();
      }

      const socket = new SockJS('http://localhost:8080/ws');
      this.stompClient = Stomp.over(socket);
      this.stompClient.connect({}, (frame) => {
        console.log('Connected: ' + frame);
        // 使用固定的 chatId 订阅
        this.stompClient.subscribe(`/topic/chat/${this.chatId}`, (message) => {
          const msg = JSON.parse(message.body);
          if (this.currentChat && msg.from !== this.selfId) {
            this.currentChat.messages.push(msg);
          }
        });
      });
    },

    /* 发送消息 */
    sendMessage() {
      if (this.newMessage.trim() === '') return;
      const uniqueId = Date.now(); // 生成唯一ID，确保是数字类型
      const message = {
        id: uniqueId,
        from: this.selfId,
        to: this.targetId,
        content: this.newMessage,
        name: this.self.name || this.self.Name,
        chatId: this.chatId, // 使用固定的 chatId
      };
      // this.currentChat.messages.push(message);
      this.newMessage = '';

      // 发送消息到后端
      if (this.stompClient && this.stompClient.connected) {
        this.stompClient.send(`/app/chat/${this.chatId}`, JSON.stringify(message));
      }
    },

    /* 加载历史聊天记录 */
    loadChatHistory() {
      request.get(`/api/chat/messages?chatId=${this.chatId}`).then(response => {
        const messages = response.data;
        this.currentChat.messages = messages;
      }).catch(error => {
        console.error('Failed to load chat history:', error);
      });
    },
  },
  beforeDestroy() {
    if (this.stompClient) {
      this.stompClient.disconnect();
    }
  },
};
</script>

<style scoped>
.chat-float {
  position: fixed;
  right: 20px;
  bottom: 20px;
  width: 360px;
  height: 420px;
  background: #fff;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.15);
  border-radius: 6px;
  display: flex;
  flex-direction: column;
  z-index: 9999;
}

.chat-header {
  height: 42px;
  line-height: 42px;
  padding: 0 12px;
  background: #409eff;
  color: #fff;
  display: flex;
  justify-content: space-between;
  align-items: center;
  border-radius: 6px 6px 0 0;
}

.chat-header i {
  cursor: pointer;
}

.chat-body {
  flex: 1;
  padding: 12px;
  overflow: auto;
}

.fade-enter-active,
.fade-leave-active {
  transition: opacity 0.3s;
}

.fade-enter,
.fade-leave-to {
  opacity: 0;
}

.chat-main {
  display: flex;
  flex-direction: column;
  height: 100%;
}

.chat-main-header {
  padding: 10px;
  background: #409eff;
  color: #fff;
}

.chat-main-body {
  flex: 1;
  padding: 10px;
  overflow: auto;
}

.chat-message {
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
}

.chat-message.other {
  align-items: flex-start;
}

.chat-message.self {
  align-items: flex-end;
}

.message-sender {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.self-sender {
  text-align: right;
}

.chat-message-content {
  display: inline-block;
  padding: 8px 12px;
  border-radius: 8px;
  max-width: 80%;
  word-wrap: break-word;
}

.chat-message.other .chat-message-content {
  background: #f0f0f0;
  color: #333;
}

.chat-message.self .chat-message-content {
  background: #409eff;
  color: #fff;
}

.chat-main-footer {
  padding: 10px;
  display: flex;
}

.chat-main-footer input {
  flex: 1;
  margin-right: 10px;
}
</style>